//
//  XDPublicView.m
//  XDUI
//
//  Created by xieyajie on 13-10-24.
//  Copyright (c) 2013年 XD. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "XDPublicView.h"

#define KVIEW_DEFAULT_WIDTH 320
#define KVIEW_DEFAULT_HEIGHT 40
#define KTITLE_DEFAULT_HEIGHT 20

#define kCommonSpaceWidth 10
#define kCommonTopMargin 10

#define KVIEW_TITLELABEL_MIN_WIDTH 60
#define KVIEW_IMAGESCROLLVIEW_HEIGHT 80
#define KACCESSORY_MAXSIZE 30

#define KFONTSIZE_TITLE 14.0
#define KFONTSIZE_DETAILTEXT 16.0

@interface XDPublicView()
{
    id _target;
    SEL _action;
    UITapGestureRecognizer *_tapRecognizer;
    
    NSMutableArray *_imageSource;
    BOOL _canEdit;
}

@property (nonatomic) XDPublicViewStyle viewStyle;
@property (strong, nonatomic) UITapGestureRecognizer *tapRecognizer;

@property (strong, nonatomic) UIButton *addImageButton;
@property (strong, nonatomic) UIScrollView *imageScrollView;

@end

@implementation XDPublicView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor whiteColor];
        _viewStyle = -1;
        
        self.viewStyle = XDPublicViewStyleDefault;
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame style:(XDPublicViewStyle)style
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor whiteColor];
        _viewStyle = -1;
        
        self.viewStyle = style;
    }
    return self;
}

- (id)initWithStyle:(XDPublicViewStyle)style
{
    CGRect frame = CGRectMake(0, 0, KVIEW_DEFAULT_WIDTH, KVIEW_DEFAULT_HEIGHT);
    self = [self initWithFrame:frame style:style];
    if (self) {
        // Initialization code
    }
    return self;
}

#pragma mark - layout subview 

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    NSInteger xOffset = 0;
    if (self.leftAccessoryView)
    {
        CGFloat leftWidth = self.leftAccessoryView.frame.size.width > KACCESSORY_MAXSIZE ? KACCESSORY_MAXSIZE : self.leftAccessoryView.frame.size.width;
        if (leftWidth == 0) {
            leftWidth = KACCESSORY_MAXSIZE;
        }
        CGFloat leftHeight = self.leftAccessoryView.frame.size.height > self.bounds.size.height ? self.bounds.size.height : self.leftAccessoryView.frame.size.height;
        if (leftHeight == 0) {
            leftHeight = KACCESSORY_MAXSIZE;
        }
        
        self.leftAccessoryView.frame = CGRectMake(xOffset + kCommonSpaceWidth / 2, (self.bounds.size.height - leftHeight) / 2, leftWidth, leftHeight);
        
        xOffset += leftWidth + kCommonSpaceWidth / 2;
    }

    NSInteger rightAccessoryWidth = 0;
    if (self.rightAccessoryView)
    {
        CGFloat rightWidth = self.rightAccessoryView.frame.size.width > KACCESSORY_MAXSIZE ? KACCESSORY_MAXSIZE : self.rightAccessoryView.frame.size.width;
        if (rightWidth == 0) {
            rightWidth = KACCESSORY_MAXSIZE;
        }
        CGFloat rightHeight = self.rightAccessoryView.frame.size.height > self.bounds.size.height ? self.bounds.size.height : self.rightAccessoryView.frame.size.height;
        if (rightHeight == 0) {
            rightHeight = KACCESSORY_MAXSIZE;
        }
        
        self.rightAccessoryView.frame = CGRectMake((self.bounds.size.width - rightWidth - kCommonSpaceWidth / 2), (self.bounds.size.height - rightHeight) / 2, rightWidth, rightHeight);
        
        rightAccessoryWidth = rightWidth + kCommonSpaceWidth / 2;
    }
    
    self.contentView.frame = CGRectMake(xOffset, 0, self.frame.size.width - xOffset - rightAccessoryWidth, self.frame.size.height);
    
    CGFloat originX = kCommonSpaceWidth;
    if (_titleLabel) {
        CGFloat titleWidth = 0;
        if (_titleLabel.text.length > 0) {
            titleWidth = KVIEW_TITLELABEL_MIN_WIDTH;
        }
        _titleLabel.frame = CGRectMake(originX, kCommonTopMargin, titleWidth, KTITLE_DEFAULT_HEIGHT);
        
        originX += self.titleLabel.frame.size.width + kCommonSpaceWidth;
        [_titleLabel sizeToFit];
    }
    
    if (_viewStyle == XDPublicViewStyleDetail) {
        _detailLabel.frame = CGRectMake(originX, kCommonTopMargin, self.contentView.frame.size.width - originX - kCommonSpaceWidth, self.contentView.frame.size.height - kCommonTopMargin * 2);
    }
    if (_viewStyle == XDPublicViewStyleImage) {
        if (!_canEdit) {
            _imageScrollView.frame = CGRectMake(originX, (self.contentView.frame.size.height - KVIEW_IMAGESCROLLVIEW_HEIGHT) / 2, self.contentView.frame.size.width - originX - kCommonSpaceWidth, KVIEW_IMAGESCROLLVIEW_HEIGHT);
        }
        else{
            CGFloat maxWidth = self.contentView.frame.size.width - originX - kCommonSpaceWidth - 70;
            NSInteger count = [_imageSource count];
            if (count <= 2) {
                _imageScrollView.frame = CGRectMake(originX, (self.contentView.frame.size.height - KVIEW_IMAGESCROLLVIEW_HEIGHT) / 2, 70 * count, KVIEW_IMAGESCROLLVIEW_HEIGHT);
                _imageScrollView.scrollEnabled = NO;
            }
            else{
                _imageScrollView.frame = CGRectMake(originX, (self.contentView.frame.size.height - KVIEW_IMAGESCROLLVIEW_HEIGHT) / 2, maxWidth, KVIEW_IMAGESCROLLVIEW_HEIGHT);
                _imageScrollView.scrollEnabled = YES;
            }

            self.addImageButton.frame = CGRectMake(originX + _imageScrollView.frame.size.width + kCommonSpaceWidth, kCommonTopMargin, 60, 60);
        }
    }
    if (_viewStyle == XDPublicViewStyleText) {
        _textView.frame = CGRectMake(originX, kCommonTopMargin, self.contentView.frame.size.width - originX - kCommonSpaceWidth, self.contentView.frame.size.height - kCommonTopMargin * 2);
    }
}

- (void)configurationViewWithStyle:(XDPublicViewStyle)style
{
    [self addSubview:self.contentView];
    [self.contentView addSubview:self.titleLabel];
    
    if (style == XDPublicViewStyleDefault) {
        
    }
    else if (style == XDPublicViewStyleDetail)
    {
        [self.contentView addSubview:self.detailLabel];
    }
    else if (style == XDPublicViewStyleImage){
        _canEdit = NO;
        [self.contentView addSubview:self.imageScrollView];
    }
    else if (style == XDPublicViewStyleText)
    {
        [self.contentView addSubview:self.textView];
    }
}

#pragma mark - setting

- (void)setViewStyle:(XDPublicViewStyle)style
{
    if (_viewStyle != style) {
        _viewStyle = style;
        [self configurationViewWithStyle:_viewStyle];
    }
}

- (void)setLeftAccessoryView:(UIView *)leftView
{
    if (_leftAccessoryView != leftView) {
        [_leftAccessoryView removeFromSuperview];
        _leftAccessoryView = leftView;
    }
    
    [self addSubview:_leftAccessoryView];
    [self layoutIfNeeded];
}

- (void)setRightAccessoryView:(UIView *)rightView
{
    if (_rightAccessoryView != rightView) {
        [_rightAccessoryView removeFromSuperview];
        _rightAccessoryView = rightView;
    }
    
    [self addSubview:_rightAccessoryView];
    [self layoutIfNeeded];
}

#pragma mark - getting

- (UIView *)contentView
{
    if (_contentView == nil) {
        _contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        _contentView.backgroundColor = [UIColor clearColor];
    }
    
    return _contentView;
}

- (UILabel *)titleLabel
{
    if (_titleLabel == nil) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(kCommonSpaceWidth, kCommonTopMargin, 0, KTITLE_DEFAULT_HEIGHT)];
        _titleLabel.backgroundColor = [UIColor clearColor];
        _titleLabel.textColor = [UIColor lightGrayColor];
        _titleLabel.font = [UIFont systemFontOfSize:KFONTSIZE_TITLE];
        
        [self.contentView addSubview:_titleLabel];
    }
    
    return _titleLabel;
}

- (UILabel *)detailLabel
{
    if (_detailLabel == nil) {
        _detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(kCommonSpaceWidth, kCommonTopMargin, self.contentView.frame.size.width - kCommonSpaceWidth * 2, self.contentView.frame.size.height - kCommonTopMargin * 2)];
        _detailLabel.numberOfLines = 0;
        _detailLabel.backgroundColor = [UIColor clearColor];
        _detailLabel.textColor = [UIColor blackColor];
        _detailLabel.font = [UIFont systemFontOfSize:KFONTSIZE_DETAILTEXT];
    }
    
    return _detailLabel;
}

- (UIScrollView *)imageScrollView
{
    if (_imageScrollView == nil) {
        CGFloat originX = self.titleLabel.frame.origin.x + self.titleLabel.frame.size.width + kCommonSpaceWidth;
        _imageScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(originX, (self.contentView.frame.size.height - KVIEW_IMAGESCROLLVIEW_HEIGHT) / 2, self.contentView.frame.size.width - kCommonSpaceWidth - originX, KVIEW_IMAGESCROLLVIEW_HEIGHT)];
        _imageScrollView.backgroundColor = [UIColor clearColor];
    }
    
    return _imageScrollView;
}

- (XDTextView *)textView
{
    if (_textView == nil) {
        CGFloat originX = self.titleLabel.frame.origin.x + self.titleLabel.frame.size.width + kCommonSpaceWidth;
        _textView = [[XDTextView alloc] initWithFrame:CGRectMake(originX, kCommonTopMargin, self.contentView.frame.size.width - originX - kCommonSpaceWidth, self.contentView.frame.size.height - kCommonTopMargin * 2)];
        _textView.backgroundColor = [UIColor clearColor];
        _textView.textColor = [UIColor blackColor];
        _textView.font = [UIFont systemFontOfSize:KFONTSIZE_DETAILTEXT];
    }
    
    return _textView;
}

- (UIButton *)addImageButton
{
    if (_addImageButton == nil) {
        _addImageButton = [[UIButton alloc] init];
        //        button.backgroundColor = [UIColor yellowColor];
        [_addImageButton setImage:[UIImage imageNamed:@"clock_addImage.png"] forState:UIControlStateNormal];
        [_addImageButton setImage:[UIImage imageNamed:@"clock_addImageHL.png"] forState:UIControlStateHighlighted];
        [_addImageButton addTarget:self action:@selector(imageViewAddAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _addImageButton;
}

- (UITapGestureRecognizer *)tapRecognizer
{
    if (_tapRecognizer == nil) {
        _tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureAction:)];
    }
    
    return _tapRecognizer;
}

#pragma mark - private

- (void)tapGestureAction:(UIGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateEnded) {
        if ([_target respondsToSelector:_action]) {
            [_target performSelector:_action withObject:nil];
        }
    }
}

#pragma mark - public

- (void)addTarget:(id)target action:(SEL)action
{
    _target = target;
    _action = action;
    
    if (_tapRecognizer == nil) {
        [self addGestureRecognizer:self.tapRecognizer];
    }
}

- (void)clearContentView
{
    if (_viewStyle == XDPublicViewStyleDefault) {
        for (UIView *view in self.contentView.subviews) {
            if (view != _titleLabel){
                [view removeFromSuperview];
            }
        }
    }
    else if (_viewStyle == XDPublicViewStyleDetail)
    {
        for (UIView *view in self.contentView.subviews) {
            if (view != _titleLabel || view != _detailLabel) {
                [view removeFromSuperview];
            }
        }
    }
    else if (_viewStyle == XDPublicViewStyleImage){
        for (UIView *view in self.contentView.subviews) {
            if (view != _titleLabel || view != _imageScrollView || view != _addImageButton) {
                [view removeFromSuperview];
            }
        }
    }
    else if (_viewStyle == XDPublicViewStyleText)
    {
        for (UIView *view in self.contentView.subviews) {
            if (view != _titleLabel || view != _textView) {
                [view removeFromSuperview];
            }
        }
    }
}

#pragma mark - default style

#pragma mark - detail style

- (CGFloat)heightWithDetailText:(NSString *)string
{
    [self layoutIfNeeded];
    
    CGFloat height = [string sizeWithFont:[UIFont systemFontOfSize:KFONTSIZE_DETAILTEXT] constrainedToSize:CGSizeMake(self.detailLabel.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping].height;
    
    return height > 20 ? (height + kCommonTopMargin * 2) : (20 + kCommonTopMargin * 2);
}

#pragma mark - textView style

- (CGFloat)measureHeight
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
    if ([self respondsToSelector:@selector(snapshotViewAfterScreenUpdates:)])
    {
        CGRect frame = self.textView.bounds;
        CGSize fudgeFactor;
        // The padding added around the text on iOS6 and iOS7 is different.
        fudgeFactor = CGSizeMake(10.0, 16.0);
        
        frame.size.height -= fudgeFactor.height;
        frame.size.width -= fudgeFactor.width;
        
        NSMutableAttributedString* textToMeasure;
        if(self.textView.attributedText && self.textView.attributedText.length > 0){
            textToMeasure = [[NSMutableAttributedString alloc] initWithAttributedString:self.textView.attributedText];
        }
        else{
            textToMeasure = [[NSMutableAttributedString alloc] initWithString:self.textView.text];
            [textToMeasure addAttribute:NSFontAttributeName value:self.textView.font range:NSMakeRange(0, textToMeasure.length)];
        }
        
        if ([textToMeasure.string hasSuffix:@"\n"])
        {
            [textToMeasure appendAttributedString:[[NSAttributedString alloc] initWithString:@"-" attributes:@{NSFontAttributeName: self.textView.font}]];
        }
        
        // NSAttributedString class method: boundingRectWithSize:options:context is
        // available only on ios7.0 sdk.
        CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                                  context:nil];
        
        return CGRectGetHeight(size) + fudgeFactor.height;
    }
    else
    {
        return self.textView.contentSize.height;
    }
#else
    return self.textView.contentSize.height;
#endif
}

- (CGFloat)heightForTextViewWithString:(NSString *)string
{
    if (string == nil || [string length] == 0) {
        return 80.0 + kCommonTopMargin * 2;
    }
    
    float fPadding = 16.0; // 8.0px x 2
    CGFloat height = [self measureHeight];
    
    return height + fPadding + kCommonTopMargin * 2;
}

- (void)setupForRemarkWithViewJump:(BOOL)jump
{
    self.textView.userInteractionEnabled = !jump;
}

#pragma mark - image style

- (CGFloat)heightForImageState
{
    return 80;
}

//不能编辑
- (void)setupWithImageSource:(NSArray *)array
{
    NSInteger count = [_imageSource count];
    if (count <= 3) {
        self.imageScrollView.scrollEnabled = NO;
        self.imageScrollView.contentSize = CGSizeMake(self.imageScrollView.frame.size.width, self.imageScrollView.frame.size.height);
    }
    else{
        self.imageScrollView.scrollEnabled = YES;
        self.imageScrollView.contentSize = CGSizeMake(count * 70, self.imageScrollView.frame.size.height);
    }
    
    for (int i = 0; i < count; i++) {
        UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(i * 70, kCommonTopMargin, 60, 60)];
        iv.image = [_imageSource objectAtIndex:i];
        iv.backgroundColor = [UIColor yellowColor];
        iv.layer.cornerRadius = 5.0;
        iv.layer.borderWidth = 1.0;
        iv.layer.borderColor = [[UIColor colorWithWhite:0.8 alpha:0.8] CGColor];
        [self.imageScrollView addSubview:iv];
    }
}

- (void)setupWithImageSource:(NSArray *)array canEdit:(BOOL)edit
{
    _canEdit = edit;
    //更新数据
    if (_imageSource == nil) {
        _imageSource = [NSMutableArray array];
    }
    [_imageSource addObjectsFromArray:array];
    
    //清空imageScrollView
    for (UIView *view in _imageScrollView.subviews) {
        [view removeFromSuperview];
    }
    
    //添加子视图
    if (!edit) {
        [_addImageButton removeFromSuperview];
        return [self setupWithImageSource:array];
    }
    else{
        NSInteger count = [_imageSource count];
        _imageScrollView.contentSize = CGSizeMake(70 * count, _imageScrollView.frame.size.height);
        
        for (int i = 0; i < count; i++) {
            UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(5 + i * 70, kCommonTopMargin, 60, 60)];
            iv.image = [_imageSource objectAtIndex:i];
            iv.backgroundColor = [UIColor yellowColor];
            iv.layer.cornerRadius = 5.0;
            iv.layer.borderWidth = 1.0;
            iv.layer.borderColor = [[UIColor colorWithWhite:0.8 alpha:0.8] CGColor];
            [self.imageScrollView addSubview:iv];
            
            UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(iv.frame.origin.x - 5, iv.frame.origin.y - 5, 20, 20)];
            button.tag = i;
            [button setImage:[UIImage imageNamed:@"clock_deleteImage.png"] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(imageViewDeleteAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.imageScrollView addSubview:button];
        }
        
        [self.contentView addSubview:self.addImageButton];
    }
}

- (void)addImageToView:(UIImage *)image
{
    if (image != nil) {
        if (_imageSource == nil) {
            _imageSource = [NSMutableArray array];
        }
        [_imageSource addObject:image];
        
        CGRect rect = self.addImageButton.frame;
        if ([_imageSource count] > 3) {
            rect = CGRectMake(([_imageSource count] - 1) * 70, kCommonTopMargin, 60, 60);
        }
        
        CGSize size = self.imageScrollView.contentSize;
        self.imageScrollView.contentSize = CGSizeMake(size.width + 70, size.height);
        
        UIImageView *iv = [[UIImageView alloc] initWithFrame:self.addImageButton.frame];
        iv.image = image;
        iv.backgroundColor = [UIColor yellowColor];
        [self.imageScrollView addSubview:iv];
        
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(iv.frame.origin.x - 5, iv.frame.origin.y - 5, 20, 20)];
        button.tag = [_imageSource count] - 1;
        [button setImage:[UIImage imageNamed:@"clock_deleteImage.png"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(imageViewDeleteAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.imageScrollView addSubview:button];
        
        if ([_imageSource count] <= 3) {
            [UIView animateWithDuration:.5f animations:^{
                self.addImageButton.frame = CGRectMake(4 * 70, kCommonTopMargin, 60, 60);
                [self.contentView addSubview:self.addImageButton];
                
                CGRect frame = self.imageScrollView.frame;
                self.imageScrollView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width + 70, frame.size.height);
            }];
        }
        else{
//            [_addImageButton removeFromSuperview];
        }
    }
}

#pragma mark - button

- (void)imageViewAddAction:(id)sender
{
    if (_imageDelegate && [_imageDelegate respondsToSelector:@selector(publicImageViewDidAddImage:)]) {
        [_imageDelegate publicImageViewDidAddImage:self];
    }
}

- (void)imageViewDeleteAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    
    if (_imageDelegate && [_imageDelegate respondsToSelector:@selector(publicImageView:didDeleteAtIndex:)]) {
        [_imageDelegate publicImageView:self didDeleteAtIndex:button.tag];
    }
}


@end
